package sample.ws.util;

import com.thoughtworks.xstream.XStream;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.namespace.QName;
import java.io.StringReader;
import java.io.StringWriter;

/**
 * ds3..
 *
 * @author Lizhong
 * @date 2019/7/13
 */

public class XmlUtil {

    public static String toXML(Object obj) {
        try {
            JAXBContext context = JAXBContext.newInstance(obj.getClass());

            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");// //编码格式
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);// 是否格式化生成的xml串
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, false);// 是否省略xm头声明信息
            StringWriter writer = new StringWriter();
            marshaller.marshal(obj, writer);
            return writer.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @SuppressWarnings("unchecked")
    public static <T> T fromXML(String xml, Class<T> valueType) {
        try {
            JAXBContext context = JAXBContext.newInstance(valueType);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            return (T) unmarshaller.unmarshal(new StringReader(xml));
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    public static String method01(Class clazz, Object obj) {
        JAXBContext context = null;
        try {
            context = JAXBContext.newInstance(clazz);
            QName q = new QName("http://www.ssii.com.cn/", "DataServiceImlp");
            JAXBElement jaxbPerson = new JAXBElement(q, clazz, obj);
            Marshaller m = null;

            m = context.createMarshaller();
            StringWriter sw = new StringWriter();
            m.marshal(jaxbPerson, sw);
            return m.toString();
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return null;
    }
public static String method01(Object result){
    //TODO 2019/7/13 17:17
    XStream xstream = new XStream();
    String xml = xstream.toXML(result);
    return xml;
}
}